import sys
import threading
import signal
import atexit
import gobject


class Daemon(object):
    def __init__(self, **kwargs):
        self.killevent = threading.Event()
        self.MainController = kwargs.get('MainController')
        signal.signal(signal.SIGINT, self.stop_daemon)
        self.daemon_thread = DaemonThread(MainController=self.MainController, killevent=self.killevent)
        self.daemon_thread.start()
        signal.pause()
    
    def stop_daemon(self, signum, frame):
        print 'got ctrl-c'
        self.killevent.set()
        
        #sys.exit(0)
        
class DaemonThread(threading.Thread):
    def __init__(self, **kwargs):
        threading.Thread.__init__(self)
        self.MainController = kwargs.get('MainController')
        self.killevent = kwargs.get('killevent')
    def run(self):
        self.MainController.comm.do_connect()
        self.killevent.wait()
        print 'closing...'
        self.MainController.on_app_exit()
        #self.MainController.comm.do_disconnect()
        #gobject.MainLoop().quit()
        #sys.exit(0)
        
if __name__ == '__main__':
    e = threading.Event()
    def on_thread():
        print 'thread start'
        #e.wait()
        signal.pause()
        print 'thread end'
    def on_exit():
        print 'onexit'
    def on_sigint(*args):
        print 'sigint', args
        e.set()
    #t = threading.Thread(target=on_thread)
    signal.signal(signal.SIGINT, on_sigint)
    atexit.register(on_exit)
    print 'start'
    signal.pause()
    #t.start()
    #e.wait()
    #print 'done'
